//
//  TUserInfoTableViewCell.m
//  LoveShare
//
//  Created by ways on 2017/5/3.
//  Copyright © 2017年 tikeyc. All rights reserved.
//

#import "TUserInfoTableViewCell.h"

#import "TImageCropperViewController.h"
#import "UIImage+Rotation.h"

@interface TUserInfoTableViewCell ()<UITextFieldDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,TImageCropperDelegate>

@property (nonatomic,strong)UIImagePickerController *pickerController;

@end

@implementation TUserInfoTableViewCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
    
    self.textField.delegate = self;
    
    [self.imageButton addTarget:self action:@selector(imageButtonClickAction:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}


#pragma mark - Action methods

- (void)imageButtonClickAction:(UIButton *)button {
    TWeakSelf(self)
    [TAlertView showWithTitle:nil
                      message:nil
            cancelButtonTitle:@"取消"
            otherButtonTitles:@[@"拍照",@"相册"]
                         type:UIAlertControllerStyleActionSheet
                andParentView:nil
                    andAction:^(NSInteger buttonIndex) {
                        if (buttonIndex == 0) {
                            NSLog(@"取消");
                        } else if (buttonIndex == 1) {
                            NSLog(@"拍照");
                            [weakself takePhotoOrSelectedPhotosAlbumWithType:1];
                        } else if (buttonIndex == 2) {
                            NSLog(@"相册");
                            [weakself takePhotoOrSelectedPhotosAlbumWithType:2];
                        }
                    }];
}


//开始拍照
-(void)takePhotoOrSelectedPhotosAlbumWithType:(NSInteger)type
{
    UIImagePickerControllerSourceType sourceType;
    if (type == 1) {
        if (![UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
            NSLog(@"模拟其中无法打开照相机,请在真机中使用");
            return;
        }
        sourceType = UIImagePickerControllerSourceTypeCamera;
    }else {
        if (![UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypePhotoLibrary]) {
            NSLog(@"模拟失败");
            return;
        }
        sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }
    
    if (!_pickerController) {
        _pickerController = [[UIImagePickerController alloc] init];
        _pickerController.delegate = (id)self;
    }
    _pickerController.sourceType = sourceType;
    if (type == 1) {
        _pickerController.showsCameraControls = YES;
    }
    //
    [self.viewController presentViewController:_pickerController animated:YES completion:NULL];
}

#pragma mark - UIImagePickerControllerDelegate

//当选择一张图片后进入这里
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info

{
    NSLog(@"选择照片...");
    UIImage *original;
    //通过UIImagePickerControllerMediaType判断返回的是照片还是视频
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    //如果返回的type等于kUTTypeImage，代表返回的是照片,并且需要判断当前相机使用的sourcetype是拍照还是相册
    if ([type isEqualToString:(NSString*)kUTTypeImage] && picker.sourceType==UIImagePickerControllerSourceTypeCamera) {
        //获取照片的原图
        original = [info objectForKey:UIImagePickerControllerOriginalImage];
        //        如果是拍照的照片，则需要手动保存到本地，系统不会自动保存拍照成功后的照片
        UIImageWriteToSavedPhotosAlbum(original, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    }else if ([type isEqualToString:(NSString*)kUTTypeImage] && picker.sourceType == UIImagePickerControllerSourceTypePhotoLibrary) {
        //获取照片的原图
        original = [info objectForKey:UIImagePickerControllerOriginalImage];
    }
    // //////////////
    TWeakSelf(self)
    [picker dismissViewControllerAnimated:YES completion:^() {
        UIImage *portraitImg = [info objectForKey:UIImagePickerControllerOriginalImage];
        portraitImg = [portraitImg imageByScalingToMaxSize];
        if (_isUserInfoIconImgCell) {
            // 裁剪
            TImageCropperViewController *imgEditorVC = [[TImageCropperViewController alloc] initWithImage:portraitImg cropFrame:CGRectMake((TScreenWidth - 200)/2, (TScreenHeight - 200)/2, 200, 200) limitScaleRatio:3.0];
            imgEditorVC.delegate = (id)self;
            //    [self presentViewController:imgEditorVC animated:YES completion:^{
            // TO DO
            //    }];
            [weakself.viewController.navigationController pushViewController:imgEditorVC animated:YES];
        } else {
            //只有编辑驾座
            [self.imageButton setImage:portraitImg forState:UIControlStateNormal];
        }
        
    }];
    
    
}


//取消照相机的回调
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    
    [picker dismissViewControllerAnimated:YES completion:NULL];
}
//保存照片成功后的回调
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    NSLog(@"saved..");
    
}

#pragma mark - ORCImageCropperDelegate
- (void)imageCropper:(TImageCropperViewController *)cropperViewController didFinished:(UIImage *)editedImage {
    //只有编辑头像设置了回调，才会回调此处
    [self.imageButton setImage:editedImage forState:UIControlStateNormal];
    //    [cropperViewController dismissViewControllerAnimated:YES completion:^{
    //        // TO DO
    //    }];
}

- (void)imageCropperDidCancel:(TImageCropperViewController *)cropperViewController {
    //    [cropperViewController dismissViewControllerAnimated:YES completion:^{
    //    }];
}


#pragma mark - UITextFieldDelegate

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    CGFloat keyboardRectHeight = 226;
    CGRect convertRect = [textField convertRect:textField.frame toView:self.myTableView];
    NSLog(@"%@",NSStringFromCGRect(convertRect));
    if (convertRect.origin.y + convertRect.size.height > keyboardRectHeight) {
        NSLog(@"move");
        CGFloat moveValue = keyboardRectHeight - (convertRect.origin.y + convertRect.size.height);
        self.myTableView.top = moveValue;
    }
    return YES;
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
    self.myTableView.top = 0;
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    self.myTableView.top = 0;
    return YES;
}

@end



